package com.cnvp.paladin.controller;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.shiro.SecurityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cnvp.paladin.core.BaseController;
import com.cnvp.paladin.core.MyCallback;
import com.cnvp.paladin.model.MessageType;
import com.cnvp.paladin.model.Room;
import com.cnvp.paladin.model.Rule;
import com.cnvp.paladin.model.SysUser;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.ICallback;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

public class MessageTypeController extends BaseController {

	public void index() {

		SysUser currentUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        int userID = currentUser.get("id");
        if (userID == 1){
            setAttr("page", MessageType.dao.paginate(getParaToInt(0, 1), 10));
        }else{
            String sql = "where userid =" + userID+" and del=0";
            setAttr("page", MessageType.dao.paginate(getParaToInt(0, 1), 10,sql));
        }
	}

	public void find() {
		Map<String, Object> json = new HashMap<String, Object>();
		if (isPost()) {
			int id = getParaToInt("messagetype.id") == null ? -1 : getParaToInt("messagetype.id");
			String msgtypename = getPara("messagetype.msgtypename");
			int userid = getParaToInt("messagetype.userid") == null ? -1 : getParaToInt("messagetype.userid");

			String findSql = "(1=1) and ";
			if (id != -1)
				findSql += "id=" + id + " and ";
			if (msgtypename != null && !msgtypename.isEmpty())
				findSql += "msgtypename like '%" + msgtypename + "%'" + " and ";
			if (userid != -1)
				findSql += "userid=" + userid + " and ";
			findSql += " (1=1);";

			List<MessageType> data = MessageType.dao.where(findSql);
			if (data.size() != 0) {
				json.put("code", "0");
				json.put("data", data);
				json.put("msg", "success");
			} else {
				json.put("code", "305");
				json.put("data", data);
				json.put("msg", "返回数据为空");
			}
		}
		renderJson(json);
	}

	public void getlist() {
		Map<String, Object> json = new HashMap<String, Object>();
		List<MessageType> data = MessageType.dao.where("");
		json.put("code", "0");
		json.put("data", data);
		json.put("msg", "success");
		renderJson(json);
		
	}

	public void create() {

		String is_app = getPara("is_app");

		if (isPost()) {

			//获取参数  msgtypename 消息模板的表名  field 创建表的sql语句
			
			String msgtypename = getPara("messagetype.msgtypename");
			String field = getPara("messagetype.field");

			if (null == msgtypename || null == field) {
				renderJson("{\"code\":\"301\",\"data\":\"\",\"msg\":\"缺少参数\"}");
			} else {

	
				Map map = new HashMap();

				HashMap<String, String> data = new HashMap<String, String>();
				Map map2 = JSON.parseObject(field);

				String Createsql = "create table cnvp_" + msgtypename + "(";

				for (Object o : map2.entrySet()) {
					Map.Entry<String, String> entry = (Map.Entry<String, String>) o;
					System.out.println(entry.getKey() + "--->" + entry.getValue());

					if (entry.getKey() != "primary key")
						Createsql += entry.getKey() + " " + entry.getValue() + ",";
					else
						Createsql += entry.getKey() + "(" + entry.getValue() + ")";
				}

				Createsql += ");";

				System.out.println(Createsql);
                
				//获取当前用户id
				SysUser currentUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
				int Userid = currentUser.get("id");

				// 获取当前时间
				Format format = new SimpleDateFormat("yyyyMMddhhmm");
				String createtime = format.format(new Date());

				String InsertSql = "insert into cnvp_message_type(msgtypename,userid,del,createtime) values('"
						+ msgtypename + "'," + Userid + ",0," + createtime + ");";

				System.out.println(InsertSql);

				// 创建表

				MyCallback callback = new MyCallback(Createsql);
				Db.execute(callback);

				//插入数据
				MyCallback callback1 = new MyCallback(InsertSql);
				Db.execute(callback1);

				
				if ("1".equals(is_app)) {
					renderJson("{\"code\":\"0\",\"data\":\"\",\"msg\":\"success\"}");
				} else {
					redirect(getControllerKey());
				}
				return;
			}

		} else {
			MessageType data = new MessageType();
			setAttr("data", data);
			render("form.html");
		}
	}

/*
	public void update() {
		String is_app = getPara("is_app");
		if (isPost()) {
			String flag = getPara("messagetype.id");
			int id = 0;
			if (flag == null && getParaToInt() != null) {
				id = getParaToInt();
			} else if (!flag.isEmpty()) {
				id = getParaToInt("messagetype.id");
			}
			MessageType mt = MessageType.dao.findById(id);
			if (mt == null) {
				renderJson("{\"code\":\"307\",\"data\":\"\",\"msg\":\"该主键不存在\"}");
			} else {
				// 检验是否非空字段全部填写
				MessageType r = getModel(MessageType.class, "messagetype").set("id", id);
				if (null == r.get("msgtypename")) {
					renderJson("{\"code\":\"301\",\"data\":\"\",\"msg\":\"缺少参数\"}");
				} else {
					if (r.update()) {
						if ("1".equals(is_app)) {
							renderJson("{\"code\":\"0\",\"data\":\"\",\"msg\":\"修改房间成功\"}");
						} else {
							redirect(getControllerKey());
						}
						return;
					}
				}
			}
		} else {
			// renderJson("{\"code\":\"301\",\"data\":\"\",\"msg\":\"缺少参数\"}");
			setAttr("data", MessageType.dao.findById(getParaToInt()));
			render("form.html");
		}
	}*/

	public void delete() {
		String is_app = getPara("is_app");
		String flag = getPara("messagetype.id");
		int id = 0;
		boolean f = false;
		if (flag == null) {
			f = true;
		}
		if (f && getParaToInt() != null) {
			id = getParaToInt();
		} else if (getParaToInt("messagetype.id") != null) {
			id = getParaToInt("messagetype.id");
		}
		MessageType mt = MessageType.dao.findById(id);
		String deleteSql="DROP TABLE cnvp_"+mt.get("msgtypename");
		
		if (mt != null) {
			
			mt.set("del", 1);
			mt.update();
			
			//删除消息模板表
			MyCallback callback1 = new MyCallback(deleteSql);
			Db.execute(callback1);
			
			if ("1".equals(is_app)) {
				renderJson("{\"code\":\"0\",\"data\":\"\",\"msg\":\"删除消息成功\"}");
			} else {
				redirect(getControllerKey());
			}
		} else {
			renderJson("{\"code\":\"307\",\"data\":\"\",\"msg\":\"该主键不存在\"}");
		}
	}

	public void deleteAll() {
		String is_app = getPara("is_app");
		Integer[] ids = null;
		if (!getPara("messagetype.id").isEmpty()) {
			ids = getParaValuesToInt("messagetype.id");
		} else {
			renderJson("{\"code\":\"307\",\"data\":\"\",\"msg\":\"该主键不存在\"}");
			return;
		}
		boolean flag = true;
		for (Integer id : ids) {
			MessageType mt = MessageType.dao.findById(id);
			String deleteSql="DROP TABLE "+mt.get("msgtypename");
			if (mt != null) {

				mt.set("del", 1);
				mt.update();
				//删除消息模板表
				MyCallback callback1 = new MyCallback(deleteSql);
				Db.execute(callback1);
			} else {
				flag = false;
			}
		}
		if ("1".equals(is_app) && flag == true) {
			renderJson("{\"code\":\"0\",\"data\":\"\",\"msg\":\"批量删除消息模板表成功\"}");
		} else if ("1".equals(is_app) && flag == false) {
			renderJson("{\"code\":\"307\",\"data\":\"\",\"msg\":\"该主键不存在\"}");
		} else {
			redirect(getControllerKey());
		}
	}
	
	
	public void showMessage(){
		
		String str=getRequest().getParameter("q");
       	
		//传字段值field
		String sql="desc cnvp_"+str;			
		List<String> fields = new ArrayList<String>();
		List<Record> column=Db.find(sql);
		for(int i=0;i<column.size();i++){
			Record r=column.get(i);
			fields.add(r.getStr("field"));
		}
		setAttr("fields", fields);
		
		//传页面page
        Page<Record> userPage = Db.paginate(1, 10, "select *", "from cnvp_"+str);
        setAttr("page", userPage);
        
        
     
		
	}
	
	


}